# coding:utf-8
# 验证码
from AnalysisService.util.DATimeUtil import DateFormatUtil
from AnalysisService.MongoUtil import MongoDB

from AnalysisService.MMKeyUtil import AVISONY_DB_NAEM,AVISONY_CAPTCHA_COLLECTION
from AnalysisService.util.Log import log


class CaptchaDB:

    def __init__(self):
        self.mongo = MongoDB(AVISONY_DB_NAEM, AVISONY_CAPTCHA_COLLECTION)

    def captchaCollection(self):

        verifications = self.mongo.find({})
        return verifications

    def query(self, filter):
        array = self.mongo.find(filter)
        return array

    def query_one(self, filter):
        one = self.mongo.find_one(filter)
        return one

    def isExist(self, filter):
        array = self.mongo.find(filter)
        if array.count() > 0:
            return True

        return False

    '''
        验证时间
    '''

    def checkTime(self, phonenumber,timeout):

        timestamp = DateFormatUtil.timestamp()
        second = timeout
        now = timestamp - second
        isbool = True

        search = {"phonenumber": phonenumber}
        users = self.query(search).sort([('createtime', -1)])

        if users.count() > 0:
            user = users.next()
            time = user['createtime']
            createtime = DateFormatUtil.toTimestamp(time)

            isbool = False

            if createtime < now:
                isbool = True

        return isbool



    '''
        验证code
    '''

    def checkCode(self, phonenumber, code):

        search = {"phonenumber": phonenumber, "captcha": code}
        users = self.query(search)
        isbool = False

        if users.count() > 0:
            isbool = True

        return isbool

    '''
      添加 短信验证码
    '''

    def add(self, phonenumber, code):

        query = {"phonenumber": phonenumber}
        self.mongo.remove(query)

        message = {

            "phonenumber": phonenumber,
            "captcha": code,
            "createtime": DateFormatUtil.format()
        }

        isbool = self.mongo.insert(message)

        log.i("获取验证码 -  ", "成功" if isbool else "失败", ' phonenumber: ', phonenumber, 'code: ', code)

        return isbool
